const fileSystem = require('fs');
const path = require('path');
const postcss = require('gulp-postcss');
const gulp = require('gulp');
const rename = require('gulp-rename');
const cssnano = require('cssnano');
const px2units = require('postcss-px2units');
const precss = require('precss');
const notify = require("gulp-notify");
const notifier = require('node-notifier');
const del = require('del')
const babel = require('gulp-babel');
var cached = require('gulp-cached');
var template = require('gulp-template');
var atImport = require("postcss-import")
var gulpWxaTpl = require("./build/gulpTpl")
const WXA_TPL = {
  name: process.env.WXAPP_TPL,
  NODE_ENV:process.env.NODE_ENV
}


const pcssPlugins = [
  atImport(),
  cssnano({autoprefixer: false, mergeRules: false, zindex: false, reduceIdents: false}),
  precss(),
  px2units()
];

const handleError = function () {
  let args = Array.prototype.slice.call(arguments);
  notify.onError({
    title: '编译错误',
    message: '<%=error.message %>'
  }).apply(this, args);//替换为当前对象
  notifier.notify({
    title: 'css 编译错误',
    message: args.message
  });
  this.emit();
}
const src = './src'
const dist = './dist'


function cleanFiles(filePath) {
  return del([filePath])
}

const removeFile = function (file) {
  if (cached.caches['base'][path.resolve(file)]) {
    delete cached.caches['base'][path.resolve(file)]
  }
  console.info("delete", file);
  let distFile = './dist/' + path.relative('./src', file); //计算相对路径
  fileSystem.existsSync(distFile) && fileSystem.unlink(distFile, (err) => {
  });
}

function copyFiles(filePath) {
  return gulp.src(filePath)
      .pipe(cached('base'))
      .pipe(gulpWxaTpl(WXA_TPL))
      .pipe(gulp.dest(dist))
}

function copyJs(filePath) {
  return gulp.src(filePath)
      .pipe(cached('base'))
      .pipe(babel({
        plugins: [[require.resolve('babel-plugin-module-resolver'), {
          root: [`./src`],
          alias: {'@src': './src', '@booking': './src/sp-booking', '@mall': './src/sp-mall'}
        }]],
      }))
      .pipe(gulpWxaTpl(WXA_TPL))
      .pipe(gulp.dest(dist))
}

function dealPostcss(filePath) {
  return gulp.src(filePath)
      .pipe(cached('base'))
      .pipe(postcss(pcssPlugins, {parser: require('postcss-comment')}))
      .on('error', handleError)
      .pipe(rename({extname: ".wxss"}))
      .pipe(gulpWxaTpl(WXA_TPL))
      .pipe(gulp.dest(dist));
}

function configJs(filePath) {
  return gulp.src(filePath)
      .pipe(template({
        tpl: WXA_TPL.name,
        NODE_ENV:WXA_TPL.NODE_ENV
      }))
      .pipe(gulp.dest(dist))
}



gulp.task('clean', () => cleanFiles(`${dist}/**`))
gulp.task('wxapp', () => copyFiles(`${src}/**/*.{json,wxss,wxml,wxs}`))
gulp.task('static', function () {
  return gulp.src(`${src}/static/**`).pipe(gulp.dest(`${dist}/static`));
})
gulp.task('js', () => copyJs([`${src}/**/*.js`, `!${src}/config.js`]))
gulp.task('config', () => configJs([`${src}/config.js`]))
gulp.task('pcss', () => dealPostcss(`${src}/**/*.pcss`));

gulp.task('watch', function () {
  gulp.watch(`${src}/**/*.pcss`)
      .on("add", gulp.series('pcss'))
      .on('change', gulp.series('pcss'))
      .on('unlink', file => removeFile(file.replace('.pcss', '.wxss')));

  gulp.watch([`${src}/**/*.js`, `!${src}/config.js`])
      .on('add', gulp.series('js'))
      .on('change', gulp.series('js'))
      .on('unlink', removeFile);
  gulp.watch([`${src}/config.js`],  gulp.series('config'))

  gulp.watch(`${src}/**/*.{json,wxss,wxml,wxs}`)
      .on('add', gulp.series('wxapp'))
      .on('change', gulp.series('wxapp'))
      .on('unlink', removeFile);

  gulp.watch(`${src}/static/**`)
      .on('add', gulp.series('static'))
      .on('change', gulp.series('static'))
      .on('unlink', removeFile)
});

gulp.task('build', gulp.series('clean', 'wxapp', 'config', 'js', 'static', 'pcss'))
gulp.task('dev', gulp.series('build', 'watch'))
